package com.panda.common.io;
/**
 * @author 常鑫毅
 */
import java.io.File;

import org.apache.log4j.Logger;


import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 文件夹压缩功能方法
 * @author 常鑫毅
 *
 */
public class ZipperUtil {
	
	private static Logger logger = Logger.getLogger(ZipperUtil.class);
	
	private String outpath;
    
	public ZipperUtil(String outpath) {
    	this.outpath=outpath;
    }

    /**
     * 压缩文件夹
     * @param inputFileName 输入一个文件夹
     * @throws Exception
     */
    public void zip(String inputFileName) throws Exception {
        String zipFileName = outpath; //打包后文件名字 "c:\\test.zip"
//        System.out.println(zipFileName);
        zip(zipFileName, new File(inputFileName));
    }

    private void zip(String zipFileName, File inputFile) throws Exception {
    	if(inputFile.exists()){
    	org.apache.tools.zip.ZipOutputStream out = new org.apache.tools.zip.ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, inputFile, "");
        logger.info("zip done");
        out.close();
    	}
    }

    private void zip(org.apache.tools.zip.ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
           File[] fl = f.listFiles();
           out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
           base = base.length() == 0 ? "" : base + "/";
           for (int i = 0; i < fl.length; i++) {
           zip(out, fl[i], base + fl[i].getName());
         }
        }else {
           out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
           FileInputStream in = new FileInputStream(f);
           int b;
//           System.out.println(base);
           while ( (b = in.read()) != -1) {
            out.write(b);
         }
         in.close();
       }
    }
    
    
    public static void main(String [] temp){
    	ZipperUtil zu = new ZipperUtil("c:/test.zip"); //指定的压缩路径
        try {
           zu.zip("c:/test");//你要压缩的文件夹
        }catch (Exception ex) {
           ex.printStackTrace();
       }
    }

}